#include "formatitem.h"

using namespace std;

FormatItem::FormatItem(Format *format,
                       FERange range,
                       void *context,
                       FreeContext free,
                       Type type,
                       const QString label,
                       const QString description,
                       FormatItem* parent)
    : format_(format), range_(range), context_(context), free_(free), type_(type), label_(label), description_(description), parent_(parent) {
}

FormatItem::~FormatItem()
{
    FormatItem *child;
    foreach (child, children_) {
        delete child;
    }
    children_.clear();

    if (context_ && free_) free_(context_);

    switch (type_) {
    case kStructureView:
        if (view_.structure_) {
            delete view_.structure_;
            view_.structure_ = nullptr;
        }
        break;
    default:
        break;
    }
}

void FormatItem::constructTree()
{
    FormatItem *item = nullptr;
    vector<SubFormat> sub_formats;
    auto ret = format_->getSubFormats(range_, context_, sub_formats);
    if (ret < 0) {
        return;
    }

    if (format_->getTopField() != nullptr) {
        item = new FormatItem(format_, range_, context_, nullptr, FormatItem::kStructureView, "Structure View", "", this);
        appendChild(item);
    }

    SubFormat sub;
    foreach (sub, sub_formats) {
        item = new FormatItem(sub.format, sub.range, sub.context, sub.free, FormatItem::kFormat, sub.format->name(), "", this);
        appendChild(item);
        item->constructTree();
    }
}

void FormatItem::appendChild(FormatItem* child) {
    children_.append(child);
}

FormatItem* FormatItem::child(int row) {
    if (row < 0 || row >= children_.size())
        return nullptr;
    return children_.at(row);
}

int FormatItem::childCount() const {
    return children_.size();
}

int FormatItem::columnCount() const {
    return 1; // 只有一列数据
}

QVariant FormatItem::data(int column) const {
    if (column == 0)
        return label_;
    return QVariant();
}

int FormatItem::row() const {
    if (parent_)
        return parent_->children_.indexOf(const_cast<FormatItem*>(this));
    return 0;
}

FormatItem* FormatItem::parent() {
    return parent_;
}

void FormatItem::show()
{
    switch (type_) {
    case kStructureView:
        if (view_.structure_) {
            view_.structure_->activateWindow();
        } else {
            view_.structure_ = new FieldDialog(format_, range_, context_);
            connect(view_.structure_, &FieldDialog::closed, this, &FormatItem::onViewClosed);
            view_.structure_->show();
        }
        break;
    default:
        break;
    }
}

int FormatItem::onViewClosed(FieldDialog *obj){
//    qDebug() << "onViewClosed";
    disconnect(obj, &FieldDialog::closed, this, &FormatItem::onViewClosed);
    delete obj;
    view_.structure_ = nullptr;
    return 0;
}
